package com.onlinevideo.util;

import cn.hutool.extra.mail.MailAccount;
import cn.hutool.extra.mail.MailUtil;
import com.onlinevideo.entity.EmailInfo;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;

public class MailInfoUtils {
    private static Properties properties = new Properties() ;
    static{
            String path = "mail.properties";
            try {
                properties.load(MailInfoUtils.class.getClassLoader().getResourceAsStream(path));
            }catch (IOException e){
                System.out.println("配置文件【" +path + "】没有找到");
            } catch (Exception e) {
                e.printStackTrace();
            }
    }

    public static MailAccount getMailAccountInfo(){
        MailAccount account = new MailAccount();
        account.setHost(properties.getProperty("host"));
        account.setPort(Integer.valueOf(properties.getProperty("port")));
        account.setAuth(true);
        account.setFrom(properties.getProperty("from"));
        account.setUser(properties.getProperty("user"));
        account.setPass(properties.getProperty("pass"));
        account.setStarttlsEnable(Boolean.parseBoolean(properties.getProperty("starttlsEnable")));
        account.setSslEnable(Boolean.parseBoolean(properties.getProperty("sslEnable")));
        account.setSocketFactoryClass(properties.getProperty("socketFactoryClass"));
        account.setSocketFactoryFallback(Boolean.parseBoolean(properties.getProperty("socketFactoryFallback")));
        account.setSocketFactoryPort(Integer.parseInt(properties.getProperty("socketFactoryPort")));
        account.setTimeout(Integer.parseInt(properties.getProperty("socketFactoryPort")));
        account.setConnectionTimeout(Integer.parseInt(properties.getProperty("socketFactoryPort")));
        return account;
    }
    public  static Boolean sendMailUtils(EmailInfo emailInfo){
        if(emailInfo.getMailboxCollection()==null||emailInfo.getMailboxCollection().size()<=0){
            return false;
        }
        if(emailInfo.getFiles()==null){
            emailInfo.setFiles(new ArrayList<>());
        }
        if(emailInfo.getFiles().size()>0){
            MailUtil.send(MailInfoUtils.getMailAccountInfo(), emailInfo.getMailboxCollection(), emailInfo.getSubject(), emailInfo.getContent(), emailInfo.getHtml(),emailInfo.getFiles().toArray(new File[emailInfo.getFiles().size()]));
        }else {
            MailUtil.send(MailInfoUtils.getMailAccountInfo(), emailInfo.getMailboxCollection(), emailInfo.getSubject(), emailInfo.getContent(), emailInfo.getHtml());
        }
        return true;
    }
}
